package cn.passlink.bletoothchat.Tools.Location;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

public class GPSHelper {



    public interface CustomLocationListener {
        void onLocationChanged(Location location);

        void onStatusChanged(String provider, int status, Bundle extras);

        void onProviderEnabled(String provider);

        void onProviderDisabled(String provider);
    }

    private Context context;
    private LocationManager locationManager;
    private CustomLocationListener customLocationListener;

    public GPSHelper(Context context) {
        this.context = context;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    public void requestLocationUpdates(CustomLocationListener listener) {
        this.customLocationListener = listener;

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

            // 设置合适的时间间隔和距离阈值   5s,5m
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 5f, locationListener);
        } else {
            // 处理权限拒绝的情况

            Toast.makeText(context, "请打开定位权限和定位功能！！！", Toast.LENGTH_SHORT).show();
            // ...
        }
    }

    public void removeLocationUpdates() {
        if (customLocationListener != null) {
            locationManager.removeUpdates(locationListener);
            customLocationListener = null;
        }
    }

    private final LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (customLocationListener != null) {
                customLocationListener.onLocationChanged(location);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if (customLocationListener != null) {
                customLocationListener.onStatusChanged(provider, status, extras);
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            if (customLocationListener != null) {
                customLocationListener.onProviderEnabled(provider);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            if (customLocationListener != null) {
                customLocationListener.onProviderDisabled(provider);
            }
        }
    };
}